import FormModal from '@/components/FormModal/index.jsx';
import { Form, Input } from 'antd';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import ModalUtil from '@/utils/modal.js';
import { getName } from '@/pages/FileManage/fun.js';
import { ResourceApi } from '@/api/resource/api.js';

function RenameModal({ onRefresh }, ref) {
  useImperativeHandle(ref, () => ({
    open: (data) => open(data),
    close: () => formRef.current?.close()
  }));

  const [form] = Form.useForm();
  const formRef = useRef(null);
  const [updateId, setUpdateId] = useState();

  // 打开弹窗
  function open(data) {
    if (data.resourceId == null) {
      ModalUtil.error('数据ID丢失，请刷新重试');
      return;
    }
    setUpdateId(data.resourceId);
    formRef.current?.open();
    form.setFieldsValue({
      fileName: getName(data)
    });
  }

  // 提交表单
  const handleSubmit = async (values) => {
    handleBeforeSubmit(values);
    const { code } = await ResourceApi.update(updateId, values);
    if (code === 0) {
      ModalUtil.success('操作成功');
      form?.resetFields();
      onRefresh && onRefresh();
      formRef.current?.close();
    }
  };

  const handleBeforeSubmit = (values) => {
    const fileName = values.fileName;
    const parts = fileName.split('.');
    if (parts.length > 1) {
      values.fileExtension = parts.pop() ?? ''; // 获取扩展名
      values.resourceName = parts.join('.') ?? ''; // 获取文件名（去掉扩展名）
    } else {
      values.resourceName = fileName;
    }
    delete values.fileName;
  };

  return (
    <FormModal
      width={450}
      form={form}
      ref={formRef}
      name="renameForm"
      title={'重命名'}
      onFinish={handleSubmit}
      formItems={
        <>
          <Form.Item
            name="fileName"
            label="文件名称"
            rules={[{ required: true, message: '请输入文件名称' }]}
          >
            <Input placeholder="请输入文件名称" />
          </Form.Item>
        </>
      }
    />
  );
}

export default forwardRef(RenameModal);
